package net.caixiaomi.info.ui.main;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mobstat.StatService;

import net.caixiaomi.info.R;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.logger.Timber;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.SchemeUtil;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.WebView4Scroll;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import butterknife.BindView;

public class FindFragment extends BaseFragment implements OnRefreshListener {
    public static final String TAG = "FindFragment";
    @BindView(R.id.container)
    LinearLayout mContainer;
    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    @BindView(R.id.title)
    TextView mTitle;
    private WebView4Scroll mWebView;
    private String mURL = "";

    public static FindFragment newInstance() {
        return new FindFragment();
    }

    @Override
    protected int fragmentLayout() {
        return R.layout.frag_find;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.app_name)).append(" · ").append(getString(R.string.bottom_find));
        mTitle.setText(stringBuilder);
        mRefresh.setOnRefreshListener(this);
//        mURL = "http://192.168.31.205:8080/" + "find?from=app_find";
        mURL = Constants.BASE_H5_URL + "faxian/zixun?from=app_find";
        mWebView = new WebView4Scroll(getActivity());
        mContainer.addView(mWebView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        WebSettings settings = mWebView.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setDisplayZoomControls(false);
        settings.setTextZoom(100);
        String ua = "";
        try {
            ua=settings.getDefaultUserAgent(getActivity());
            ua="app/android&"+ua;
        } catch (NoSuchMethodError e) {
        }
        Timber.d("UA " + ua);
        settings.setUserAgentString(ua);

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        mWebView.setWebViewClient(mWebClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.setViewGroup(mRefresh);
        loadData();

    }

    private void loadData() {
        if (TextUtils.isEmpty(mURL)) {
            return;
        }

        // 是否有HTTP前辍
        if (!mURL.startsWith("http") && !mURL.startsWith("file")) {
            mURL = "http://" + mURL;
        }
        StringBuilder url = new StringBuilder(mURL);
        if (url.indexOf("?") < 0) {
            url.append("?");
        }

        if (url.indexOf("showtitle") < 0) {
            url.append("&").append("showtitle=").append("1");
        }
        if (url.indexOf("showBar") < 0) {
            url.append("&").append("showBar=").append("1");
        }
        mURL = url.toString();
        mWebView.loadUrl(mURL);
        Timber.d("url == " + mURL);
    }

    private WebViewClient mWebClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Timber.d("shouldOverrideUrlLoading url == " + url);
            return SchemeUtil.parseInWebViewUrl(getActivity(), url, null);
        }


        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            try {
                ToastUtil.s(R.string.C_NET_ERROR);
                view.setVisibility(View.GONE);
                super.onReceivedError(view, errorCode, description, failingUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            //TODO 需要注入token信息
        }

    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
            this.openFileChooser(uploadMsg);
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
            this.openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        }

        public void onReceivedTitle(WebView view, String title) {
        }
    };

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mWebView.reload();
        mRefresh.finishRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        StatService.onPageStart(getActivity(),"faxian-view");
    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPageEnd(getActivity(),"faxian-view");
    }

}
